import os from '@packages/lib-os';
import { matchByPathname } from '@packages/lib-router';

import appBridge from './wptBridge/oldVersion/appBridge';

// h5与其他平台的配置路由映射配置
// - appUrl 表示app注册的url [number|function]  appUrl在最终跳转的时候会添加 location.host
// - xcxUrl 表示小程序注册的url [number|function]
// 最终的到的结果为空时，会走h5页面
export const routerConfig = {
    // '/': {
    //     appUrl: '/webApp/discovery',
    //     xcxUrl: '/pages/index/index',
    //     dyXcxUrl: '/pages/index/index',
    //     bdXcxUrl: '/pages/index/index',
    // },
    // '/home': {
    //     appUrl: '/webApp/discovery',
    //     xcxUrl: '/pages/index/index',
    //     dyXcxUrl: '/pages/index/index',
    //     bdXcxUrl: '/pages/index/index',
    // },
    // '/shop/:uri': {
    //     appUrl(params, url) {
    //         const { showCoupon } = WPT.Util.query(url);
    //         return WPT.Util.urlAddQuery(`/shop/${params.uri}`, { showCoupon });
    //     },
    //     xcxUrl(params, url) {
    //         const { showCoupon } = WPT.Util.query(url);
    //         return WPT.Util.urlAddQuery(`/pages/shop/index/index?uri=${params.uri}`, { showCoupon });
    //     },
    //     dyXcxUrl(params) {
    //         return `/pages/shop/index/index?uri=${params.uri}`;
    //     },
    //     bdXcxUrl(params) {
    //         return `/pages/shop/index/index?uri=${params.uri}`;
    //     },
    // },
};

/**
 * 执行App任务，等待App完成WKWebviewBridge js注入
 * @exports execAppJob
 * @param {Function} callback 成功回调函数
 */
export function execAppJob(callback) {
    if (window.wptLoadJsSuccess) {
        callback && callback();
    } else {
        $(document).on('wptLoadJs:success', callback);
    }
}

export async function transXcxPath(url) {
    const matchResult = matchByPathname(url, routerConfig);
    if (!matchResult) {
        return false;
    }
    const router = matchResult.value;
    if (router.xcxUrl) {
        let xcxUrl = router.xcxUrl;
        if ($.isFunction(xcxUrl)) {
            xcxUrl = xcxUrl(matchResult.params, url);
        }
        xcxUrl = await xcxUrl;
        return xcxUrl && xcxUrl.replace(/^\/?/, '/');
    }
    return false;
}

/**
 * 是否可以使用原生化的xcx/app页面，如果可以的话直接跳转走
 * @exports jumpToExternal
 * @param {String} url 页面路径
 * @param {Boolean} [fromShowPage=false] 记录历史？
 * @returns {Boolean} 是否执行成功
 */
export function jumpToExternal(url, fromShowPage) {
    if (
        WPT.os.modalWebview &&
        WPT.os.appVersion >= 384 &&
        (WPT.Util.query(url).innerActivityJumpType == 2 || WPT.Util.query().innerActivityJumpType == 2)
    ) {
        return false;
    }
    // 跳到外部
    const matchResult = matchByPathname(url, routerConfig);
    if (!matchResult || /^\/h5\//i.test(matchResult.url)) {
        return false;
    }
    const router = matchResult.value;

    const getParams = (href) => {
        const { r, c, pos } = WPT.Util.query(href);
        const params = {
            r,
            c,
            pos,
        };
        return WPT.Util.filterKeys(params, 'r', 'c', 'pos');
    };

    if (os.wpt && router.appUrl) {
        // app端
        if (
            os.wptAppVerison < 136 &&
            !['/webApp/discovery', '/home', '/recommend', '/attention'].includes(matchResult.router)
        ) {
            // 1.3.6版本以前 只有首页才跳转app。
            return false;
        }

        let appUrl = router.appUrl;
        if (url == '/home?r=menu_home' || url == '/webApp/discovery?r=menu_home') {
            // 如果是 这个地址 就是app的首页，
            appUrl = '/index';
        }

        if ($.isFunction(router.appUrl)) {
            appUrl = router.appUrl(matchResult.params, url);
            if (!appUrl) {
                return false;
            }
        }
        execAppJob(() => {
            Promise.resolve(appUrl).then((_appUrl) => {
                appBridge.jump(
                    window.location.host + _appUrl,
                    (result) => {
                        if (result == '0') {
                            fromShowPage ? WPT.showPageInWeb(url) : WPT.redirect(url, true);
                        }
                    },
                    getParams(url)
                );
            });
        });

        return true;
    }
    const { wx, tt, swan } = window;
    if (
        (os.xcx || os.dyXcx || os.jzgXcx || os.bdXcx) &&
        (router.xcxUrl || router.dyXcxUrl || router.jzgXcxUrl || router.bdXcxUrl)
    ) {
        let xcxUrl = router.xcxUrl;
        if (os.dyXcx) {
            xcxUrl = router.dyXcxUrl;
        }

        if (os.jzgXcx) {
            xcxUrl = router.jzgXcxUrl;
        }

        if (os.bdXcx) {
            xcxUrl = router.bdXcxUrl;
        }

        if ($.isFunction(xcxUrl)) {
            xcxUrl = xcxUrl(matchResult.params, url);
        }

        if (!xcxUrl) {
            return false;
        }
        if (tt && tt.miniProgram && tt.miniProgram.reLaunch) {
            tt.miniProgram.navigateTo({ url: WPT.Util.urlAddQuery(xcxUrl, getParams(url)) });
            return true;
        }
        if (wx && wx.miniProgram && wx.miniProgram.reLaunch) {
            // 进来首页就是小程序页面的时候不能直接唤起小程序，延迟200
            WPT.execWxJob(() => {
                Promise.resolve(xcxUrl).then((_xcxUrl) => {
                    const isReLaunch =
                        ['/pages/my/index/index', '/pages/category/index/index', '/pages/index/index'].some((i) =>
                            _xcxUrl.startsWith(i)
                        ) && WPT.Util.query(url).reLaunch != 0;

                    wx.miniProgram[isReLaunch ? 'reLaunch' : 'navigateTo']({
                        url: WPT.Util.urlAddQuery(_xcxUrl, getParams(url)).replace('r=weishi-weishi', 'r=weishi'),
                    });
                });
            });
            return true;
        }

        if (swan && swan.webView && swan.webView.reLaunch) {
            Promise.resolve(xcxUrl).then((_xcxUrl) => {
                if (WPT.Util.query().fr_ == 'qxbdxcx') {
                    const { pathname, query = {} } = WPT.Util.urlParse(_xcxUrl);
                    const { fr_, ...q } = query;
                    const path = WPT.Util.urlAddQuery(pathname, { ...q, ...getParams(url) });
                    swan.navigateToSmartProgram({
                        appKey: '83bmdknsV5258lhZ1nGiae0BPFiSpuPU',
                        path,
                    });
                    return;
                }
                const isReLaunch =
                    ['/pages/my/index/index', '/pages/category/index/index', '/pages/index/index'].some((i) =>
                        _xcxUrl.startsWith(i)
                    ) && WPT.Util.query(url).reLaunch !== 0;

                swan.webView[isReLaunch ? 'reLaunch' : 'navigateTo']({
                    url: WPT.Util.urlAddQuery(_xcxUrl, getParams(url)),
                });
            });
            return true;
        }

        return false;
    }

    return false;
}
